package com.vision.web.listener;

import com.vision.cache.impl.OnlineCache;
import com.vision.common.bean.UserMsg;
import com.vision.common.util.HttpIPUtil;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author zhongchao
 * @title
 * @Date 2017/05/27
 */
@WebListener
public class SessionListenerHandler implements HttpSessionListener {

    @Resource
    private OnlineCache onlineCache;

    @Autowired
    private HttpServletRequest request;

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        UserMsg userMsg = new UserMsg();
        String ipAddr = HttpIPUtil.getIpAddr(request);
        userMsg.setIp(ipAddr);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userMsg.setRequestTime(simpleDateFormat.format(new Date()));
        userMsg.setSessionId(httpSessionEvent.getSession().getId());
        onlineCache.addCache(userMsg);
        ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
        Integer num = (Integer) servletContext.getAttribute("num");
        if (num == null) {
            servletContext.setAttribute("num", 1);
        } else {
            servletContext.setAttribute("num", num + 1);
        }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        String sessionId = session.getId();
        onlineCache.updateCache(sessionId);
        ServletContext servletContext = session.getServletContext();
        Integer num = (Integer) servletContext.getAttribute("num");
        if (num != null) {
            servletContext.setAttribute("num", num - 1);
        }
    }

}
